﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Reflection.Emit;
using System.Windows.Forms;

namespace L9SubSet
{
	class DxfInOutClass
	{
		[DllImport("kernel32.dll")]
		public static extern IntPtr LoadLibrary(string lpFileName);
		
		[DllImport("kernel32.dll")]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
		
		[DllImport("kernel32.dll")]
		public static extern bool FreeLibrary(IntPtr hModule);

		[DllImport("kernel32.dll")]
		public static extern uint GetLastError();

		private IntPtr hModule = IntPtr.Zero;
		private IntPtr farProc = IntPtr.Zero;

		private delegate int ParseDXF(int id, string str1, byte[] data, string str2);
		
		// 加载 DLL
		public bool LoadDxfDll()
		{
			string pathfile = getAppPath() + @"\dxf32.dll";
			
			hModule = LoadLibrary(pathfile);
			if (hModule == IntPtr.Zero)
			{
				MessageBox.Show("LoadDxfDll Error, hModule is NULL", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Information);
				return false;
			}
			
			farProc = GetProcAddress(hModule, "parseDXF");
			if (farProc == IntPtr.Zero)
			{
				MessageBox.Show("LoadDxfDll Error, farProc is NULL", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Information);
				return false;
			}
			
			return true;
		}
		
		// 卸载 DLL
		public bool FreeDxfDll()
		{
			if (hModule != IntPtr.Zero)
			{
				FreeLibrary(hModule);
				return true;
			}
			else
			{
				return false;
			}
		}
		
		// 将 dxf 文件解析为 bin 文件
		public bool GetDxfData(string srcFileName)
		{
			bool loadflg = LoadDxfDll();
			if (loadflg == false)
			{
				return false;
			}

			ParseDXF parseDxf = (ParseDXF)Marshal.GetDelegateForFunctionPointer(farProc, typeof(ParseDXF));

			string outfile = getAppPath() + @"\dxfParse.bin";
			byte[] data = new byte[10];
			parseDxf(3, srcFileName, data, outfile);

			bool freedllflg = FreeDxfDll();
			if (freedllflg == false)
			{
				return false;
			}
			
			return true;
		}

		// 获得应用程序 exe 所在路径
		private string getAppPath()
		{
			return (new FileInfo(Application.ExecutablePath)).Directory.ToString();
		}
	}
}
